package com.superjson.showpro.service.impl;

import com.superjson.showpro.base.GenericServiceImpl;
import com.beantools.util.ObjectUtil;
import com.beantools.util.StringUtil;
import com.superjson.showpro.dao.UserDao;
import com.superjson.showpro.entity.User;
import com.superjson.showpro.service.UserService;
import com.superjson.showpro.shared.exception.GeneralBizException;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultUtil;
import com.superjson.showpro.shared.util.CommonUtil;
import com.superjson.showpro.shared.util.CryptUtil;
import com.superjson.showpro.shared.util.IpUtill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import static com.superjson.showpro.shared.enums.SignInTypeEnum.SIGN_IN_TYPE_ENTERPRISE;
import static com.superjson.showpro.shared.result.ResultCodeEnum.SIGN_IN_FAIL;

@Service
public class UserServiceImpl extends GenericServiceImpl<User> implements UserService {

    private UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        super(userDao);
        this.userDao = userDao;
    }

    @Override
    public Result saveUser(User user, HttpServletRequest request) {
        if (ObjectUtil.isNull(user)) {
            throw new GeneralBizException(SIGN_IN_FAIL);
        }
        user.setPassword(CryptUtil.encrypt(user.getPassword()));
        if (user.getSignInType().equals(SIGN_IN_TYPE_ENTERPRISE) && StringUtil.isBlank(user.getCompanyName())) {
            throw new GeneralBizException("企业用户，企业名称不能为空");
        }
        user.setAccountName(CommonUtil.getRandomAccountName());
        user.setToken(request.getSession().getId());
        user.setSignInIp(IpUtill.getIpAddr(request));
        user.setSignIn(true);
        userDao.save(user);
        return ResultUtil.buildSuccess();
    }

    @Override
    public Result<User> existUser(String phoneOrAccName, String companyName) {
        if (StringUtil.isAnyBlank(phoneOrAccName)) {
            return  ResultUtil.buildFailed("手机号不能为空");
        }
        return ResultUtil.buildSuccess(userDao.existUser(phoneOrAccName, companyName));
    }

    @Override
    public Result<User> getByAccNameOrPhone(String phoneOrAccName, String password) {
        return ResultUtil.buildSuccess(userDao.getByAccNameOrPhone(phoneOrAccName, password));
    }
}